package Administracion;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author pato
 */
public final class ventas2 extends javax.swing.JFrame {

    PreparedStatement ps;
    ResultSet rs;
    DefaultTableModel dtm;
    ResultSetMetaData rsm;
    int idUsuario;
    int client = -1;
    String fi = null, ff = null, tipopago = null;
    int sucursal = -1, usuario = -1;

    /**
     * Creates new form ventas
     */
    public ventas2(int code, String FI, String FF, int suc, int user, String pag) {
        initComponents();
        client = code;
        fi = FI;
        ff = FF;
        sucursal = suc;
        usuario = user;
        tipopago = pag;
        /* jTable1.getColumnModel().getColumn(0).setMaxWidth(50);
         jTable1.getColumnModel().getColumn(1).setMaxWidth(50);*/
        jTextField1.setDocument(new LimitadorCaracteres());
        jTextField1.requestFocus();/*
         jTable2.getColumnModel().getColumn(0).setMaxWidth(40);
         jTable2.getColumnModel().getColumn(1).setMaxWidth(40);
         jTable2.getColumnModel().getColumn(2).setPreferredWidth(80);
         jTable2.getColumnModel().getColumn(4).setMaxWidth(50);
         jTable2.getColumnModel().getColumn(5).setMaxWidth(50);
         jTable2.getColumnModel().getColumn(6).setMaxWidth(50);
         jTable2.getColumnModel().getColumn(3).setMaxWidth(100);*/

        // Detalle.setEnabled(false);
        cargarDatos();
    }

    void cargarDatos() {
        try {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
            dtm = (DefaultTableModel) this.jTable1.getModel();
            dtm.setRowCount(0);
            String como = "", where = "";
            if (client != -1) {
                como += " id_cliente =" + client + " and";
            }
            if (usuario != -1) {
                como += " id_usuario =" + usuario + " and";
            }
            if (sucursal != -1) {
                como += " sucursal =" + sucursal + " and";
            }
            if (tipopago != null) {
                if (tipopago.equals("Efectivo")) {
                    como += " (tipopago ='Efectivo' or tipopago = 'Credito') and";
                } else {
                    como += " tipopago ='" + tipopago + "' and";
                }
            }
            if (ff != null) {
                como += " (fecha between '" + fi + "' and '" + ff + "') and";
            }
            como += (jTextField1.getText().equals("")) ? " 1 = 1" : " folio like " + jTextField1.getText();
            ps = local_connection.getconnect().prepareStatement("select  folio, ticket, detalle,fecha, sucursal from venta where " + como + " order by fecha desc");
            rs = ps.executeQuery();
//            rsm = (com.mysql.jdbc.ResultSetMetaData) (ResultSetMetaData) rs.getMetaData();
            ArrayList<Object[]> data = new ArrayList<>();
            while (rs.next()) {
                Object[] rows = new Object[jTable1.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                data.add(rows);
            }
            for (int i = 0; i < data.size(); i++) {
                dtm.addRow(data.get(i));
            }
        } catch (SQLException ex) {
            Logger.getLogger(ventas2.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        vendedort = new javax.swing.JLabel();
        clientet = new javax.swing.JLabel();
        pesot = new javax.swing.JLabel();
        netot = new javax.swing.JLabel();
        descuentot = new javax.swing.JLabel();
        totalt = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        tipopagot = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        Detalle = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconImage(new ImageIcon(getClass().getResource("/Imagenes/logo_rayito.png")).getImage());

        jTextField1.setText(" ");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Folio", "Numero", "Detalles", "Fecha", "Sucursal"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTable1KeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel2.setText("Vendedor:");

        jLabel4.setText("Cliente:");

        jLabel5.setText("Peso Total (GR):");

        jLabel6.setText("Total Neto $:");

        jLabel7.setText("Descuento $:");

        jLabel8.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel8.setText("$");

        vendedort.setText("---");

        clientet.setText("---");

        pesot.setText("----");

        netot.setText("---");

        descuentot.setText("---");

        totalt.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        totalt.setText("---");

        jLabel1.setText("Tipo de pago:");

        tipopagot.setText("------");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tipopagot)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(pesot))
                            .addComponent(clientet)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel6)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel8)
                                        .addComponent(jLabel7)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(netot)
                                    .addComponent(totalt)
                                    .addComponent(descuentot, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(vendedort)))
                        .addContainerGap(76, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tipopagot))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(vendedort))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(clientet)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(pesot))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(netot))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(descuentot))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(totalt))
                .addGap(0, 9, Short.MAX_VALUE))
        );

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Cantidad", "Nombre", "Descuento", "P-Unit", "Importe", "Peso"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable2);

        Detalle.setText("Detalle");
        Detalle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DetalleActionPerformed(evt);
            }
        });

        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(Detalle, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 562, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2))
            .addComponent(jScrollPane2)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(Detalle)
                            .addComponent(jButton1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 8, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    void consultarVentas() {
        dtm = (DefaultTableModel) this.jTable1.getModel();
        dtm.setRowCount(0);
        String como = "", where = "";
        try {
            if (client != -1) {
                como += " id_cliente =" + client + " and";
            }
            if (usuario != -1) {
                como += " id_usuario =" + usuario + " and";
            }
            if (sucursal != -1) {
                como += " sucursal =" + sucursal + " and";
            }
            if (tipopago != null) {
                como += " tipopago ='" + tipopago + "' and";
            }
            if (ff != null) {
                como += " (fecha between '" + fi + "' and '" + ff + "') and";
            }
            como += (jTextField1.getText().equals("")) ? " 1 = 1" : " folio like " + jTextField1.getText();
            ps = local_connection.getconnect().prepareStatement("select  folio, ticket,detalle, fecha, sucursal from venta where " + como + " order by fecha desc");
            rs = ps.executeQuery();
            //System.out.println(ps.toString());
            ArrayList<Object[]> data = new ArrayList<>();

            while (rs.next()) {
                Object[] rows = new Object[jTable1.getColumnCount()];
                for (int i = 0; i < rows.length; i++) {
                    rows[i] = rs.getObject(i + 1);
                }
                data.add(rows);
            }

            for (int i = 0; i < data.size(); i++) {
                dtm.addRow(data.get(i));
            }

        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }

    class LimitadorCaracteres extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        @Override
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!Character.isDigit(arg1.charAt(i))) {
                    return;
                }
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        consultarVentas();
// TODO add your handling code here:
    }//GEN-LAST:event_jTextField1KeyReleased

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        seleccion();
        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1MouseClicked
    void seleccion() {
        int row = jTable1.getSelectedRow();
        if (row != -1) {
            try {
                String cliente = "", usuario = "", tipo = "";
                float total = 0, neto = 0, descuento = 0;
                int peso = 0;
                dtm = (DefaultTableModel) this.jTable2.getModel();
                dtm.setRowCount(0);
                ArrayList<Object[]> data = new ArrayList<>();
                Object[] rows = new Object[jTable2.getColumnCount()];
                int codigo = (int) (jTable1.getValueAt(row, 0));
                ps = local_connection.cn.prepareStatement("select productos.id_producto,cantidad,if(detalleventa.id_producto=-2,(select nombre from otros where detalle_venta = idetalle),productos.nombre) as nombre,\n"
                        + "modo,preciovendido,(preciovendido*cantidad) as importe,(productos.peso*cantidad) as peso,\n"
                        + "concat(c.nombre,' ',c.paterno,' ',c.materno) as cliente,\n"
                        + "concat(u.nombre,' ',u.paterno,' ',u.materno) as usuario, ticket, tipopago\n"
                        + "from venta join detalleventa on detalleventa.folio= venta.folio \n"
                        + "join productos on productos.id_producto = detalleventa.id_producto join personas c on venta.id_cliente= c.id_persona \n"
                        + "join personas u on venta.id_usuario = u.id_persona where detalleventa.folio = ?");
                ps.setInt(1, codigo);
                rs = ps.executeQuery();
                while (rs.next()) {
                    rows[0] = rs.getString("id_producto");
                    rows[1] = rs.getFloat("cantidad");
                    rows[2] = rs.getString("nombre");
                    rows[3] = rs.getString("modo");
                    rows[4] = rs.getFloat("preciovendido");
                    rows[5] = rs.getFloat("importe");
                    rows[6] = rs.getInt("peso");
                    data.add(rows);
                    peso += (int) rows[6];
                    if ((float) rows[5] > 0) {
                        neto += (float) rows[5];
                    } else {
                        descuento += (float) rows[5];
                    }
                    dtm.addRow(data.get(0));
                    cliente = rs.getString("cliente");
                    usuario = rs.getString("usuario");
                    tipo = rs.getString("tipopago");
                }
                data.clear();
                total = neto + descuento;
                tipopagot.setText(tipo);
                clientet.setText(cliente);
                vendedort.setText(usuario);
                netot.setText(String.valueOf(neto));
                totalt.setText(String.valueOf(total));
                pesot.setText(String.valueOf(peso));
                descuentot.setText(String.valueOf(descuento));

                //cargar datos al jTable2
            } catch (SQLException ex) {
                Logger.getLogger(ventas2.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyReleased
        seleccion();        // TODO add your handling code here:
    }//GEN-LAST:event_jTable1KeyReleased

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void DetalleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DetalleActionPerformed

        int row = jTable1.getSelectedRow();
        if (row != -1) {
            ModificarDetalleVenta modDetalle = new ModificarDetalleVenta((Integer) jTable1.getValueAt(row, 0));
            modDetalle.setVisible(true);
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_DetalleActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Detalle;
    private javax.swing.JLabel clientet;
    private javax.swing.JLabel descuentot;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JLabel netot;
    private javax.swing.JLabel pesot;
    private javax.swing.JLabel tipopagot;
    private javax.swing.JLabel totalt;
    private javax.swing.JLabel vendedort;
    // End of variables declaration//GEN-END:variables
}
